package myself.login.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import myself.login.service.LoginService;
import myself.util.MD5;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 登陆界面Controller
 * 
 * */
@Controller
public class LoginController {

	Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Resource
	private LoginService loginService;

	// 通过Action访问该方法 来返回login.jsp页面
	@RequestMapping(value = "/login")
	public ModelAndView login(HttpServletRequest request) {
		// getContextPath是找目录名
		// System.out.println(request.getContextPath());
		return new ModelAndView("WEB-INF/jsp/login/login.jsp");
	}

	// 验证 登陆用户名和密码是否正确
	// @ResponseBody 可以将内容或对象 作为返回的数据.
	@RequestMapping(value = "/validation", method = RequestMethod.GET)
	public @ResponseBody String validation(HttpServletRequest request,
			@RequestParam("userCode") String userCode,
			@RequestParam("passWord") String passWord,
			@RequestParam("userName") String userName) {
		// 接收userName 判断是学生还是老师
		if ("studentName".equals(userName)) {
			// 查找是否存在userName.
			int i = loginService.qrystudentCode(userCode);

			if (i == 1) {
				// 通过userName查找passWord是否正确.

				String password = loginService.qryPassWord(userCode);

				if (password.equals(passWord)) {

					// 将studentCode 存到session里面 getSession来获取session的值
					// String studentName =
					// loginService.qryStudentName(studentCode);
					HttpSession session = request.getSession();
					session.setAttribute("userCode", userCode);
					return "1";
				}
			}
		} else if ("teacherName".equals(userName)) {

			int i = loginService.qryteacherCode(userCode);

			if (i == 1) {
				//暂时先只有 老师 MD5 加密 
				passWord = new MD5().getMD5ofStr(passWord);
				String password = loginService.qrytPassWord(userCode);
				if (password.equals(passWord)) {

					HttpSession session = request.getSession();
					session.setAttribute("userCode", userCode);
					return "3";
				}
			}
		}
		return "2";
	}
}
